<template>
  <div>
    <template v-if="!readonly">
      <el-tag
        v-for="tag in tags"
        :key="tag"
        class="mx-1"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
        round
      >
        {{ tag }}
      </el-tag>
      <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="ml-1 w-2"
        size="small"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
        + New Tag
      </el-button>
    </template>
    <template v-else>
      <el-tag
        v-for="tag in readonlyTag"
        :key="tag"
        type="warning"
        class="mx-1"
        :disable-transitions="false"
        @close="handleClose(tag)"
        round
      >
        {{ tag }}
      </el-tag>
    </template>
  </div>
</template>

<script lang="ts" setup>
import {nextTick, ref} from 'vue'
import {ElInput} from 'element-plus'
import {usePublicCompStore} from "@/store/modules/publicComponents";
import {storeToRefs} from "pinia";

const props = defineProps({
  tags: {
    type: String,
    default: ""
  },
  readonly: {
    type: Boolean,
    default: false
  }
})


const PublicComStore = usePublicCompStore()
const {tags} = storeToRefs(PublicComStore)
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
let readonlyTag = []

// 如果不是只读的，并且tag不为空，则进行赋值
if (props.readonly && props.tags != "") {
  readonlyTag = props.tags.split(',')
}

const handleClose = (tag: string) => {
  tags.value.splice(tags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    tags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>
